import { ObjectLiteral, SelectQueryBuilder } from "typeorm";
import { PaginateOptions, PaginateReturn } from "../entity/EntityConfig/types";

export  const paginate = async <E extends object>(qb: SelectQueryBuilder<E>, options: PaginateOptions) => {
    //页数
    const start = options.page > 0 ? options.page - 1 : 0
    //获取查询的总数
    const TotalNum = await qb.getCount()
    //跟据查询的条件查询的数据(每页的数据)
    const PageData =await qb.take(start).skip(start * options.limit).getMany()
    //获取所有
    const items = await qb.getMany();
    //获取总页数
    const TotalPage = Math.ceil(TotalNum / options.limit)
    //每页的记录数
    const CountNumber = TotalNum % options.limit == 0 ? TotalNum % options.limit : options.limit
    //  这行代码计算当前页的记录数，如果当前页不是最后一页，则记录数为每页显示的记录数 
    const ItemCount = options.page < TotalPage ? options.limit : CountNumber

    return {
        items,
        mate:{
            TotalNum,
            ItemCount,
            perNumber: CountNumber,
            TotalPage,
    
        }
     
    }

}

/**
 * 数据手动分页函数
 * @param options 分页选项
 * @param data 数据列表
 */
export function manualPaginate<E extends ObjectLiteral>(
    options: PaginateOptions,
    data: E[],
): PaginateReturn<E> {
    const { page, limit } = options;
    let items: E[] = [];
    const totalItems = data.length;
    const totalRst = totalItems / limit;
    const totalPages =
        totalRst > Math.floor(totalRst) ? Math.floor(totalRst) + 1 : Math.floor(totalRst);
    let itemCount = 0;
    if (page <= totalPages) {
        itemCount = page === totalPages ? totalItems - (totalPages - 1) * limit : limit;
        const start = (page - 1) * limit;
        items = data.slice(start, start + itemCount);
    }
    return {
        meta: {
            itemCount,
            totalItems,
            perPage: limit,
            totalPages,
            currentPage: page,
        },
        items,
    }
}
